/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package alex;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.entity.XYItemEntity;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataset;

import dao.TagDAO;
import domain.Tag;

/**
 *
 * @author Alex
 */
public class WordDiffs extends javax.swing.JFrame {
    private String selectedWord;
    private Integer CategoryID;
    private String[][] WordMap = null;
    private List<Tag> AllWordsTagList = null; //Only used for ashimas grid

    // e.g. WordMap[0][0]="TheWord"; WordMap[0][1]="DistanceFromSelected"; WordMap[0][2]="CountOfWord";
    /**
     * Creates new form WordDiffs
     */
    private void NewSelf(String selectedWord)
    {
    	WordDiffs whatever = new WordDiffs(selectedWord, this.CategoryID, this.AllWordsTagList);
    	whatever.setVisible(true);
    	this.dispose();
    }

    //(TheSelectedWord, TheTagIDToSelect)
    public WordDiffs(String selectedWord, Integer CategoryID, List<Tag> AllWords) {
        this.selectedWord = selectedWord;
        this.CategoryID = CategoryID;
        this.AllWordsTagList = AllWords;
        initComponents();
        // <editor-fold defaultstate="collapsed" desc="VISUAL ONLY">
        jLabel1.setText("Selected Word: " + this.selectedWord);
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="GET lEVENSHTEIN + WORDS">
        this.getWords(AllWords);
        this.getLevenshtein();
        this.sortWords();
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="CREATE GRAPH">
        CategoryDataset barData = createBarDataset();
        JFreeChart barChart = createBarChart(barData);
        ChartPanel barChartPanel = new ChartPanel(barChart);
        barChartPanel.addChartMouseListener(new ChartMouseListener(){
			@Override
			public void chartMouseClicked(ChartMouseEvent arg0) {
				// TODO Auto-generated method stub

				try{
					CategoryItemEntity xyitem= (CategoryItemEntity)arg0.getEntity(); // get clicked entity
					/*Dont judge me*/
					String [] a = xyitem.getToolTipText().split(",");
					String [] b = a[1].split("=");
					String c = b[0].trim().substring(0,b[0].trim().length()-1).trim();
					NewSelf(c);
					
				}catch(Exception e)
				{
					JOptionPane.showMessageDialog(getContentPane(),"Please click on one of the red bars.");
				}

				
			}
			@Override
			public void chartMouseMoved(ChartMouseEvent arg0) {
			}
        });
        
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="ADD GRAPH TO PANEL">
        barChartPanel.setPreferredSize(new Dimension(chartPanel.getWidth(), chartPanel.getHeight()));
        chartPanel.removeAll();
        chartPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        chartPanel.add(barChartPanel);
        // </editor-fold>
        
        // <editor-fold defaultstate="collapsed" desc="POPULATE DROP DOWN">
        DistanceDropDown.removeAllItems();
        for(Integer i =0; i < this.WordMap.length; i++)
        {
            DistanceDropDown.addItem(this.WordMap[i][1]+":"+this.WordMap[i][0]);
        }
        // </editor-fold>

    }  
    // <editor-fold defaultstate="collapsed" desc="SORT WORDS">
    private void sortWords()
    {
        boolean hasMoved = true;
        while(hasMoved)
        {
            hasMoved=false;
            for(Integer i = 1; i < this.WordMap.length; i++)
            {
                if(Integer.parseInt(this.WordMap[i][1]) < Integer.parseInt(this.WordMap[i-1][1]))
                {
                    hasMoved = true;
                    String tmp;
                    for(Integer a = 0; a < this.WordMap[i].length; a++)
                    {
                        tmp="";
                        tmp = this.WordMap[i][a];
                        this.WordMap[i][a] = this.WordMap[i-1][a];
                        this.WordMap[i-1][a] = tmp;
                        
                    }
                }
                
                if(Integer.parseInt(this.WordMap[i][1]) == Integer.parseInt(this.WordMap[i-1][1]))
                {
                    Integer compare = -1;
                    compare = this.WordMap[i][1].compareTo(this.WordMap[i-1][1]);
                    if(compare < 0)
                    {
                        hasMoved = true;
                        String tmp;
                        for(Integer a = 0; a < this.WordMap[i].length; a++)
                        {
                            tmp="";
                            tmp = this.WordMap[i][a];
                            this.WordMap[i][a] = this.WordMap[i-1][a];
                            this.WordMap[i-1][a] = tmp;
                        }
                    }                 
                }
                
                
                
            }            
        }
        
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CALCULATE LEVENSHTEIN getLevenshtein()">
    private void getLevenshtein()
    {
       DistanceMatrix dist = new DistanceMatrix();
       for(Integer i = 0; i < WordMap.length; i++)
       {
           dist.setWordA(this.selectedWord);
           dist.setWordB(this.WordMap[i][0]);
           
           this.WordMap[i][1] = Integer.toString(dist.getLevenshtein());
           System.out.println("Word A:" + this.selectedWord + " Word B:" + this.WordMap[i][0] + " Diff:" + dist.getLevenshtein());
       }
       
    }// </editor-fold>
   
    // <editor-fold defaultstate="collapsed" desc="GET WORDS FROM DB getWords()">
    private void getWords(List<Tag> AllWords)
    {
    	/*String[] WORDS =  { "art", "australia", "baby", "beach", "birthday", "blue", "bw", "california", "canada", "canon",
                "cat", "chicago", "china", "christmas", "city", "dog", "england", "europe", "family", "festival", "flower", "flowers", "food",
                "france", "friends", "fun", "germany", "holiday", "india", "italy", "japan", "london", "me", "mexico", "music", "nature",
                "new", "newyork", "night", "nikon", "nyc", "paris", "park", "party", "people", "portrait", "sanfrancisco", "sky", "snow",
                "spain", "summer", "sunset", "taiwan", "tokyo", "travel", "trip", "uk", "usa", "vacation", "water", "wedding" };
           this.WordMap = new String[WORDS.length][3];
           
           for(Integer i = 0; i < WORDS.length; i++)
           {           
               this.WordMap[i][0] = WORDS[i];
           }*/
       
       
       this.WordMap = new String[AllWords.size()][3];
       
       for(Integer i = 0; i < AllWords.size(); i++)
       {           
           this.WordMap[i][0] = AllWords.get(i).getTag();
       }
       
    }// </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CREATE DATA FOR GRAPH createBarDataset()">
    private CategoryDataset createBarDataset()
    {
        DefaultCategoryDataset returnDataset = new DefaultCategoryDataset();
        for(Integer i =0; i < this.WordMap.length; i++)
        {
            returnDataset.addValue(Integer.parseInt(this.WordMap[i][1]), "Series 1", this.WordMap[i][0]);
        }
                
        return returnDataset;
    }// </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="SET VISUAL ASPECTS OF GRAPH createBarChart(CategoryDataset barData)">
    private JFreeChart createBarChart(CategoryDataset barData)
    {
        JFreeChart barChart = ChartFactory.createBarChart(
            "Close Words",         // chart title
            "Words",               // domain axis label
            "Distance",                  // range axis label
            barData,                  // data
            PlotOrientation.VERTICAL, // orientation
            false,                     // include legend
            true,                     // tooltips?
            false                     // URLs?
        );
        CategoryPlot thePlot = (CategoryPlot)barChart.getPlot();
        CategoryAxis xAxis = (CategoryAxis)thePlot.getDomainAxis();
	xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        
        return barChart;
    }// </editor-fold>
     /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        ShowMatrix = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        chartPanel = new javax.swing.JPanel();
        DistanceDropDown = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Selected Word: Fill At Runtime");

        jButton1.setText("Done");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });


        ShowMatrix.setText("Show Table");
        ShowMatrix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShowMatrixActionPerformed(evt);
            }
        });

        jButton3.setText("Show Grid");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout chartPanelLayout = new javax.swing.GroupLayout(chartPanel);
        chartPanel.setLayout(chartPanelLayout);
        chartPanelLayout.setHorizontalGroup(
            chartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 564, Short.MAX_VALUE)
        );
        chartPanelLayout.setVerticalGroup(
            chartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 271, Short.MAX_VALUE)
        );

        DistanceDropDown.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel2.setText("Distance:Word");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chartPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(DistanceDropDown, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ShowMatrix)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chartPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(ShowMatrix)
                    .addComponent(jButton3)
                    .addComponent(DistanceDropDown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void ShowMatrixActionPerformed(java.awt.event.ActionEvent evt) {                                           
        DistanceMatrixPanel pnl = new DistanceMatrixPanel(this.selectedWord,(String)DistanceDropDown.getSelectedItem());
        pnl.setVisible(true);   
    }                                          

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    	com.cloud.WordDiff whatever = new com.cloud.WordDiff(this.selectedWord, this.AllWordsTagList);
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    	this.dispose();
    }

    /**
     * @param args the command line arguments
     */
   /* public static void main(String args[]) {
     
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(WordDiffs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(WordDiffs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(WordDiffs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(WordDiffs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new WordDiffs("MyWordForm",1).setVisible(true);
            }
        });
    }*/
    // Variables declaration - do not modify
    private javax.swing.JComboBox DistanceDropDown;
    private javax.swing.JButton ShowMatrix;
    private javax.swing.JPanel chartPanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration
}
